package com.ruoyi.system.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.system.utils.AESEncryption.decrypt;
import static com.ruoyi.system.utils.AESEncryption.hexStringToByteArray;

public class AnalysisXml {
    public static HashMap authenticationXml(String filePath){
        try {
            // 创建文档构建器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析 XML 文件
            Document document = builder.parse(new File(filePath)); // 替换为你的文件路径
            document.getDocumentElement().normalize();

            // 使用 HashMap 存储 k-v 对
            HashMap<String, String> dataMap = new HashMap<>();

            // 解析 Header 元素
            NodeList headerList = document.getElementsByTagName("Header");
            Element header = (Element) headerList.item(0);
            dataMap.put("Country", header.getAttribute("country"));
            dataMap.put("Creation Date", header.getAttribute("creationdate"));
//            dataMap.put("level", header.getAttribute("level"));
//            dataMap.put("type", header.getAttribute("type"));
            dataMap.put("Email", header.getAttribute("email"));
            dataMap.put("Licensee", header.getAttribute("licensee"));
            dataMap.put("Name", header.getAttribute("name"));
            dataMap.put("Shooting Range", header.getAttribute("shootingrange"));
            dataMap.put("Username", header.getAttribute("username"));

            // 解析 Championship 元素
            NodeList championshipList = document.getElementsByTagName("Championship");

            Element championship = (Element) championshipList.item(0);
            dataMap.put("Championship Name ", championship.getAttribute("name"));
            dataMap.put("Championship Start Date ", championship.getAttribute("startdate"));
            dataMap.put("Championship End Date ", championship.getAttribute("enddate"));
            dataMap.put("Championship Level ", championship.getAttribute("level"));
            dataMap.put("Championship Type ", championship.getAttribute("level"));
//            dataMap.put("level", header.getAttribute("level"));
//            dataMap.put("type", header.getAttribute("level"));

            // 解析 Release 元素
            NodeList releaseList = document.getElementsByTagName("Release");
            for (int i = 0; i < releaseList.getLength(); i++) {
                Element release = (Element) releaseList.item(i);
                dataMap.put("Release Actual Release " + i, release.getAttribute("actualrelease"));
                dataMap.put("Release Actual Subrelease " + i, release.getAttribute("actualsubrelease"));
            }

            // 解析 XmlProperties 元素
            NodeList xmlPropertyList = document.getElementsByTagName("XmlProperty");
            for (int i = 0; i < xmlPropertyList.getLength(); i++) {
                Element xmlProperty = (Element) xmlPropertyList.item(i);
                dataMap.put("XmlProperty Name " + i, xmlProperty.getAttribute("name"));
                dataMap.put("XmlProperty Value " + i, xmlProperty.getAttribute("value"));
            }

            // 解析 Signature 元素
            NodeList signatureList = document.getElementsByTagName("Signature");
            if (signatureList.getLength() > 0) {
                Element signature = (Element) signatureList.item(0);
                String signatureValue = signature.getElementsByTagName("SignatureValue").item(0).getTextContent();
                dataMap.put("Signature Value", signatureValue);

                // 解析 DigestValue
                NodeList referenceList = signature.getElementsByTagName("Reference");
                if (referenceList.getLength() > 0) {
                    Element reference = (Element) referenceList.item(0);
                    String digestValue = reference.getElementsByTagName("DigestValue").item(0).getTextContent();
                    dataMap.put("Digest Value", digestValue);
                }
            }
            // 输出存储的数据
//            for (String key : dataMap.keySet()) {
//                System.out.println(key + ": " + dataMap.get(key));
//            }

            String encryptedText = dataMap.get("Signature Value");
            String hexKey = dataMap.get("Digest Value");
            byte[] recoveredKeyBytes = hexStringToByteArray(hexKey);
            SecretKey recoveredSecretKey = new SecretKeySpec(recoveredKeyBytes, "AES");
            String str = decrypt(encryptedText, recoveredSecretKey);
            Map<String, String> resultMap = new HashMap<>();
            String[] parts = str.split("StartTime:|EndTime:|name:|GameControl:");

            if (parts.length == 5) { // 确保分割出5个部分
                resultMap.put("StartTime", parts[1].trim());
                resultMap.put("EndTime", parts[2].trim());
                resultMap.put("name", parts[3].trim());
                resultMap.put("GameControl", parts[4].trim());
            }

            String value = "";
            for (int i = 1; i <= 6; i++) {

                if (dataMap.get("XmlProperty Value " + i).equals("true")) {
                    value = value + "1";
                } else {
                    value = value + "0";
                }
            }

            if(resultMap.get("name").equals(dataMap.get("Name"))
                    && resultMap.get("StartTime").equals(dataMap.get("Championship Start Date "))
                    && resultMap.get("EndTime").equals(dataMap.get("Championship End Date "))
                    && resultMap.get("GameControl").equals(value)) {
                    dataMap.put("Access", Boolean.toString(true));
                    return dataMap;
            }else {
                dataMap.put("Access", Boolean.toString(false));
                return dataMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }
}
